package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.BatchEditDataPermissionDTO;
import com.xbongbong.paas.pojo.dto.DetailSpecialPermissionDTO;
import com.xbongbong.paas.pojo.dto.RoleAddDTO;
import com.xbongbong.paas.pojo.dto.RoleAppDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleCopyDTO;
import com.xbongbong.paas.pojo.dto.RoleDataPermissionEditDTO;
import com.xbongbong.paas.pojo.dto.RoleDeleteDTO;
import com.xbongbong.paas.pojo.dto.RoleDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleEditNameDTO;
import com.xbongbong.paas.pojo.dto.RoleListDTO;
import com.xbongbong.paas.pojo.dto.RoleModuleDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleSaveDTO;
import com.xbongbong.paas.pojo.dto.SaveSpecialPermissionDTO;
import com.xbongbong.paas.pojo.vo.DetailSpecialPermissionVO;
import com.xbongbong.paas.pojo.vo.RoleAddVO;
import com.xbongbong.paas.pojo.vo.RoleAppDetailVO;
import com.xbongbong.paas.pojo.vo.RoleCopyVO;
import com.xbongbong.paas.pojo.vo.RoleDataPermissionEditVO;
import com.xbongbong.paas.pojo.vo.RoleDeleteVO;
import com.xbongbong.paas.pojo.vo.RoleDetailVO;
import com.xbongbong.paas.pojo.vo.RoleEditNameVO;
import com.xbongbong.paas.pojo.vo.RoleListVO;
import com.xbongbong.paas.pojo.vo.RoleModuleDetailVO;
import com.xbongbong.paas.pojo.vo.RoleSaveVO;
import com.xbongbong.paas.service.RoleService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.role.pojo.dto.RoleRecoveryDTO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 角色相关接口
 * @author kaka
 * @time 2018-8-17 16:15
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    /**
     * 获取角色列表
     * @param roleListDTO 关联DTO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid RoleListDTO roleListDTO, BindingResult br) throws Exception {
        XbbResponse<RoleListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleListVO roleListVO = roleService.list(roleListDTO);
                response = new XbbResponse<>(roleListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 删除角色
     * @param roleDeleteDTO 关联DTO
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid RoleDeleteDTO roleDeleteDTO, BindingResult br) throws Exception {
        XbbResponse<RoleDeleteVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleDeleteVO roleDeleteVO = roleService.delete(roleDeleteDTO);
                response = new XbbResponse<>(roleDeleteVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 新建角色，新建的角色权限为空
     * @param roleAddDTO 关联DTO
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid RoleAddDTO roleAddDTO, BindingResult br) throws Exception {
        XbbResponse<RoleAddVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleAddVO roleAddVO = roleService.add(roleAddDTO);
                response = new XbbResponse<>(roleAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 复制角色，复制的角色权限与被复制角色相同
     * @param roleCopyDTO 关联DTO
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String copy(@RequestBody @Valid RoleCopyDTO roleCopyDTO, BindingResult br) throws Exception {
        XbbResponse<RoleCopyVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleCopyVO roleCopyVO = roleService.copy(roleCopyDTO);
                response = new XbbResponse<>(roleCopyVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 获取角色权限清单
     * @param roleDetailDTO 关联DTO
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String detail(@RequestBody @Valid RoleDetailDTO roleDetailDTO, BindingResult br) throws Exception {
        XbbResponse<RoleDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleDetailVO roleDetailVO = roleService.detail(roleDetailDTO);
                response = new XbbResponse<>(roleDetailVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 角色管理，获取某角色对应的应用权限情况，并对该角色是否具有应用列表中的应用的权限进行标记
     */
    @RequestMapping(value = "/appDetail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String appDetail(@RequestBody @Valid RoleAppDetailDTO roleAppDetailDTO, BindingResult br) throws Exception {
        XbbResponse<RoleAppDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleAppDetailVO roleAppDetailVO = roleService.appDetail(roleAppDetailDTO);
                response = new XbbResponse<>(roleAppDetailVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 角色管理，获取某角色对应的应用权限情况， 用于批量修改数据权限
     */
    @RequestMapping(value = "/batchAppDetail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String batchAppDetail(@RequestBody @Valid RoleAppDetailDTO roleAppDetailDTO, BindingResult br) throws Exception {
        XbbResponse<RoleAppDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleAppDetailVO roleAppDetailVO = roleService.batchAppDetail(roleAppDetailDTO);
                response = new XbbResponse<>(roleAppDetailVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 角色管理，获取某角色对应的某应用应用权限情况，并对该角色是否具有应用中的表单/报表的权限进行标记
     */
    @RequestMapping(value = "/moduleDetail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String moduleDetail(@RequestBody @Valid RoleModuleDetailDTO roleModuleDetailDTO, BindingResult br) throws Exception {
        XbbResponse<RoleModuleDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleModuleDetailVO roleModuleDetailVO = roleService.moduleDetail(roleModuleDetailDTO);
                response = new XbbResponse<>(roleModuleDetailVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        // 关闭 fastJson “循环引用检测”
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 修改角色名称（目前兼容了新建角色[只填角色名]逻辑）
     * @param roleEditNameDTO 关联DTO
     */
    @RequestMapping(value = "/editName", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String editName(@RequestBody @Valid RoleEditNameDTO roleEditNameDTO, BindingResult br) throws Exception {
        XbbResponse<RoleEditNameVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleEditNameVO roleEditNameVO = roleService.editName(roleEditNameDTO);
                response = new XbbResponse<>(roleEditNameVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 修改角色数据权限，系统角色不能修改数据权限
     * @param dataPermissionEditDTO 关联DTO
     */
    @RequestMapping(value = "/editDataPermission", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String editDataPermission(@RequestBody @Valid RoleDataPermissionEditDTO dataPermissionEditDTO, BindingResult br) throws Exception {
        XbbResponse<RoleDataPermissionEditVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleDataPermissionEditVO dataPermissionEditVO = roleService.editDataPermission(dataPermissionEditDTO);
                response = new XbbResponse<>(dataPermissionEditVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 批量编辑数据权限
     * @param batchEditDataPermissionDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batchEditDataPermission", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String batchEditDataPermission(@RequestBody @Valid BatchEditDataPermissionDTO batchEditDataPermissionDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO dataPermissionEditVO = roleService.batchEditDataPermission(batchEditDataPermissionDTO);
                response = new XbbResponse<>(dataPermissionEditVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * 编辑角色权限
     * @param roleSaveDTO 关联DTO
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String save(@RequestBody @Valid RoleSaveDTO roleSaveDTO, BindingResult br) throws Exception {
        XbbResponse<RoleSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleSaveVO roleSaveVO = roleService.save(roleSaveDTO);
                response = new XbbResponse<>(roleSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * Description: 特殊权限保存（组织架构）
     * @param saveSpecialPermissionDTO
     * @param br
     * @return java.lang.String
     * @author 魏荣杰
     * @date 2020/5/28 11:05 上午
     * @since
     */
    @RequestMapping(value = "/saveSpecial", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saveSpecial(@RequestBody @Valid SaveSpecialPermissionDTO saveSpecialPermissionDTO, BindingResult br) throws Exception {
        XbbResponse<RoleSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                RoleSaveVO roleSaveVO = roleService.saveSpecial(saveSpecialPermissionDTO);
                response = new XbbResponse<>(roleSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * Description: 特殊权限展示（组织架构）
     * @param detailSpecialPermissionDTO
     * @param br
     * @return java.lang.String
     * @author 魏荣杰
     * @date 2020/5/28 11:05 上午
     * @since
     */
    @RequestMapping(value = "/detailSpecial", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String detailSpecial(@RequestBody @Valid DetailSpecialPermissionDTO detailSpecialPermissionDTO, BindingResult br) throws Exception {
        XbbResponse<DetailSpecialPermissionVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                DetailSpecialPermissionVO detailSpecialPermissionVO = roleService.detailSpecial(detailSpecialPermissionDTO);
                response = new XbbResponse<>(detailSpecialPermissionVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    @RequestMapping(value = "/sysRecovery", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String sysRecovery(@RequestBody @Valid RoleRecoveryDTO roleRecoveryDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO recoveryVO = roleService.recovery(roleRecoveryDTO);
                response = new XbbResponse<>(recoveryVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
